# -*- coding:utf-8 -*-
# request.json()练习
"""
爬虫：
目标网站
http://www.beijingprice.cn/jfcx/sp/index.shtml?ItemCode=E000002
任务需求
将 序号	时间	批发价格	农贸零售价格	超市零售价格抓取
"""

import requests
import json


class VegetableData(object):
    def __init__(self):
        self.url = "http://www.beijingprice.cn:8086/price/premiumQuery/PriceQueryDataThree/getItemData?jsoncallback=jQuery09857630674268962_1694870923896&itemCode=E000002&_=1694870923898"
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36"
        }

    # 向目标网站发起请求
    def get_data_index(self):
        resp = requests.get(self.url, headers=self.headers)
        if resp.status_code == 200:
            return resp.text
        else:
            return None

    # 解析数据
    def parse_data(self, response):
        new_resp = response.replace("jQuery09857630674268962_1694870923896(", "").replace(")", "")
        dict_data = json.loads(new_resp)[2]["tableList"]
        result = 1
        for data in dict_data:
            price_one = data["Price02"]
            price_two = data["Price03"]
            price_three = data["Price04"]
            time = data["PriceDate"]
            print(
                f"序号：{result} 时间：{time} 批发价格: {price_one} 农贸零售价格: {price_two} 超市零售价格: {price_three}")
            result += 1

    # 实现
    def main(self):
        response = self.get_data_index()
        self.parse_data(response)


if __name__ == '__main__':
    data = VegetableData()
    data.main()
